<template>
    <div class="login-container">
        <!-- 标题容器 -->
        <div class="title-container">
            <h1 class="page-title">欢迎登录</h1>
        </div>

        <!-- 卡片内容 -->
        <el-card class="box-card">
            <div slot="header" class="clearfix">
                <span class="login-title">登录</span>
            </div>
            <el-form :model="loginForm" :rules="rules" ref="loginForm" label-width="80px">
                <el-form-item label="用户名" prop="username">
                    <el-input v-model="loginForm.username" placeholder="请输入用户名" prefix-icon="el-icon-user"></el-input>
                </el-form-item>
                <el-form-item label="密码" prop="password">
                    <el-input type="password" v-model="loginForm.password" placeholder="请输入密码" show-password
                        prefix-icon="el-icon-lock"></el-input>
                </el-form-item>
                <el-form-item class="button-group">
                    <el-button type="primary" @click="submitForm('loginForm')" class="login-button">登录</el-button>
                    <el-button @click="resetForm('loginForm')" class="reset-button">重置</el-button>
                    <el-button @click="goToRegister" class="register-button">注册</el-button>
                </el-form-item>
            </el-form>
        </el-card>
    </div>
</template>

<script>
import axios from 'axios';

export default {
    data() {
        return {
            loginForm: {
                username: '',
                password: ''
            },
            rules: {
                username: [
                    { required: true, message: '请输入用户名', trigger: 'blur' }
                ],
                password: [
                    { required: true, message: '请输入密码', trigger: 'blur' }
                ]
            }
        };
    },
    methods: {
        // 提交表单方法
        async submitForm(formName) {
            this.$refs[formName].validate(async (valid) => {
                if (valid) {
                    try {
                        const res = await axios.post('http://localhost:3000/api/auth/indexLogin', this.loginForm);
                        console.log('Received login response:', res.data);

                        // 存储 token 到 localStorage
                        localStorage.setItem('token', res.data.token);

                        // 解码 JWT 获取 userId
                        const payload = JSON.parse(atob(res.data.token.split('.')[1]));
                        const userId = payload.user.id;

                        // 存储 userId 到 localStorage
                        localStorage.setItem('userId', userId);

                        this.$message.success('登录成功');
                        this.$router.push('/buyBooks');
                    } catch (err) {
                        console.error('Login request failed:', err);
                        this.$message.error('登录失败，请检查用户名和密码');
                    }
                } else {
                    console.log('Form validation failed!');
                    return false;
                }
            });
        },
        // 重置表单方法
        resetForm(formName) {
            this.$refs[formName].resetFields();
        },
        // 跳转到注册页面
        goToRegister() {
            this.$router.push('/indexSign');
        },
        // 获取个人资料方法
        async fetchProfileData() {
            try {
                // 从 Vuex 中获取用户ID
                const userId = this.$store.state.userId;

                if (!userId) {
                    throw new Error('用户ID未找到');
                }

                const response = await axios.get(`http://localhost:3000/api/setting/profile/${userId}`);
                const { username, email } = response.data;

                // 更新表单数据
                this.profileForm = {
                    avatar: 'https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png', // 假设头像固定
                    nickname: username,
                    email: email,
                };
            } catch (error) {
                console.error('获取个人资料失败:', error);
                this.$message.error('获取个人资料失败，请重试');
            }
        }
    }
};
</script>

<style scoped>
.login-container {
    display: flex;
    flex-direction: column;
    /* 垂直布局 */
    justify-content: center;
    align-items: center;
    height: 100vh;
    background: linear-gradient(135deg, #6a11cb, #2575fc);
    animation: fadeIn 1s ease-in-out;
}

/* 标题容器样式 */
.title-container {
    margin-bottom: 20px;
    /* 标题与卡片之间的间距 */
    text-align: center;
}

.page-title {
    font-size: 32px;
    font-weight: bold;
    color: #ffffff;
    text-shadow: 2px 2px 4px rgba(0, 0, 0, 0.3);
    /* 添加阴影效果 */
}

.box-card {
    width: 400px;
    border-radius: 15px;
    box-shadow: 0 10px 20px rgba(0, 0, 0, 0.2);
    background-color: #ffffff;
    animation: slideIn 0.8s ease-in-out;
}

.login-title {
    font-size: 24px;
    font-weight: bold;
    color: #333;
}

.el-form-item__label {
    color: #555;
}

.el-input {
    border-radius: 8px;
}

.button-group {
    display: flex;
    justify-content: space-between;
}

.login-button,
.reset-button,
.register-button {
    flex: 1;
    margin-right: 10px;
    border-radius: 8px;
}

.login-button {
    background-color: #6a11cb;
    border-color: #6a11cb;
}

.login-button:hover {
    background-color: #4a00e0;
    border-color: #4a00e0;
}

.reset-button,
.register-button {
    background-color: #f5f5f5;
    border-color: #ddd;
    color: #333;
}

.reset-button:hover,
.register-button:hover {
    background-color: #ddd;
    border-color: #ccc;
}

.register-button {
    margin-right: 0;
    /* 去掉最后一个按钮的右边距 */
}

@keyframes fadeIn {
    from {
        opacity: 0;
    }

    to {
        opacity: 1;
    }
}

@keyframes slideIn {
    from {
        transform: translateY(-50px);
        opacity: 0;
    }

    to {
        transform: translateY(0);
        opacity: 1;
    }
}
</style>